import os
import json
import pandas as pd
pd.set_option('display.max_rows', None)
pd.set_option('display.width', 5000)
import simplejson
import com
from conf import setting
today_time=com.time_saveandget()

def ths(ths_dic:dict)->dict:
    ths_pandas = pd.DataFrame(json.loads(ths_dic)['data']["list"])
    #pandasTore正则化
    def ths_pandas_re(ths_pandas: dict) -> dict:
        a = ths_pandas
        a.rename(
            columns={"change": "涨幅", "change_reason": "行业", "change_section": "几天", "change_days": "几板",
                     "hot_rank_chg": "增长",
                     "circulate_market_value": "市值"}, inplace=True)
        a["市值"] = pd.to_numeric(a["市值"])
        a["市值"] = round(a["市值"] / 100000000, 2)  # 一亿，保留2位
        ths_pandas_re = a[["name", "涨幅", "行业", "几天", "几板", "市值", "price", "增长", "code", "hot_rank"]]
        """change                    100 non-null object
        change_days               100 non-null object
        change_reason             100 non-null object
        change_section            100 non-null object
        change_type               100 non-null object
        circulate_market_value    100 non-null object
        code                      100 non-null object
        hot_rank                  100 non-null int64
        hot_rank_chg              100 non-null int64
        market_id                 100 non-null object
        name                      100 non-null object
        price                     100 non-null object
        stock_cnt                 100 non-null int64
        """
        return ths_pandas_re
    ths_pandas_re=ths_pandas_re(ths_pandas)
    #保存文件com.save(ths_pandas_re,time)#->pandas 与时间同时传入，保存文件
    com.save(ths_pandas_re,today_time,"ths")
    return ths_pandas_re
def dfcf(dfcf_dic:dict)->dict:
    dfcf_pandas = pd.DataFrame(json.loads(dfcf_dic)['data'])

    com.save(dfcf_pandas,today_time,"dfcf")
    return dfcf_pandas
def dxw_dictolist(dxw_dic:dict)->dict:#针对requests.yidong()
    dxw_dic = dxw_dic.encode('utf-8').decode('unicode_escape')
    dxw_pd= pd.DataFrame(json.loads(dxw_dic)['data']['name'])
    return dxw_pd[0].tolist()#['水果蔬菜', '期货', '旅游', '医药商业', '北京冬奥', '冷链物流', '区块链', '有机硅']
class zhangting:#dxw
    def __init__(self):
        pass
    def jiexi(dxw_dic:dict)->dict:
        dxw_dic = dxw_dic#encode('utf-8').decode('unicode_escape')
        dxw_dic=simplejson.loads(dxw_dic, strict=False)
        dxw_dic=dxw_dic["data"]["stock_list"]["list"]
        return dxw_dic
    def dxw_bml(json):
        #变美丽
        df_list = []
        df = pd.DataFrame()
        for i in range(len(json)):
            df_ = pd.DataFrame(json[i])
            df_text = df_.text[:16].values.tolist()
            df_text = df_text + df_[:1]["remark"].values.tolist()#增加2列
            df_bug=df_[:1]["param"].values.tolist()
            df_text.append(df_bug)
            df_4_5 = df_[4:5]["param"].values#增加板块
            df_text.append(df_4_5)
            new = pd.DataFrame([df_text])
            df=pd.concat([df,new])
        df = df.rename(
            columns={0: '股票', 1: '现价', 2: '涨停时刻', 3: '几天几板', 4: '板块(涨停数)', 5: '封单(元)', 6: '换手率', 7: '量比', 8: '主力资金',
                     9: '股性', 10: '开板次数', 11: '板上成交额', 12: '成交额', 13: '流通值', 14: '总市值', 15: '昨涨幅', 16: '揭秘', 17: 'code',
                     18: '行业'})
        return df
    def main(dxw_dic):
        dxw_list=zhangting.jiexi(dxw_dic)
        df=zhangting.dxw_bml(dxw_list)
        return df


def dxw_yidong_save(dic_:dict,i_day:str,path:str):
    #字典不等长pd.DataFrame(dict([(k, pd.Series(v)) for k, v in d.items()]))
    yidong_path = os.path.join(setting.BATH_PATH,'db','dxw','{}'.format(path),'{}.json'.format(i_day))
    yidong_pd=pd.DataFrame(dict([(k, pd.Series(v)) for k, v in dic_.items()])).T
    yidong_pd.to_csv("{}".format(yidong_path), encoding="utf-8")

def dxw_path_save(dic_:dict,i_day:str,path:str):
    path_=os.path.join(setting.BATH_PATH,'db','dxw','{}'.format(path))

    if not os.path.exists(path_):
        os.mkdir(path_)
    user_json = os.path.join(path_,'{}.json'.format(i_day))

    dic_.to_csv("{}".format(user_json), encoding="utf-8")


if __name__ == '__main__':
    pass